package org.frog.sgs.server;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.frog.sgs.io.SgsMsg;

/**
 * @author duanxiangqi
 * @date 2012-10-20
 */
public class ServerIoHandler implements IoHandler {

	private static Logger logger = Logger.getLogger(ServerIoHandler.class);

	private SgsServer server;

	public void sessionCreated(IoSession session) throws Exception {
		server.getInstance().getCharacterManager().enter(session);
	}

	public void messageReceived(IoSession session, Object obj) throws Exception {
		ServerMsgDispatcher.instance.dispatch(session, (SgsMsg) obj, server.getInstance());
	}

	public void messageSent(IoSession session, Object obj) throws Exception {}

	public void sessionClosed(IoSession session) throws Exception {
		server.getInstance().getCharacterManager().leave(session);
		logger.info("sessionClosed:" + session.getRemoteAddress());
	}

	public void exceptionCaught(IoSession session, Throwable throwable) throws Exception {
		logger.error("exceptionCaught " + throwable.getMessage());
		throwable.printStackTrace();
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {}

	public void sessionOpened(IoSession session) throws Exception {}

	public SgsServer getServer() {
		return server;
	}

	public void setServer(SgsServer server) {
		this.server = server;
	}
}
